<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import { FENGHUA_AREAS } from "@/common/general.js";
import { add_company, get_company, update_company, delete_company } from '@/api/company.js';
import { loginStore } from "@/stores/loginStore.js";

const store = loginStore();

const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

const formData = ref({
    companyname: '',
    creditcode: '',
    subdistrict: '',
    address: '',
    linkman: '',
    phone: '',
    remark: '',
    create_by: '',
    update_by: ''
});

const rules = {
    name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    contact: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
};

// 获取公司信息列表
const getcompanylist = async () => {
    await get_company({}).then(res => {
        tableData.value = res.data.detail.data;
        console.log(tableData.value);
    });
}

// 页面初始化，获取公司信息列表
onMounted(async () => {
    getcompanylist();
})

const tableData = ref([]);

const filteredTableData = computed(() => {
    return tableData.value.filter(
        (item) =>
            !searchKeyword.value || item.companyname.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.creditcode.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.subdistrict.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.address.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.linkman.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.phone.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
           item.remark.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

const handleAdd = () => {
    isEdit.value = false;
    formData.value = {
        companyname: '',
        creditcode: '',
        subdistrict: '',
        address: '',
        linkman: '',
        phone: '',
        remark: '',
        create_by: store.login_name,
        update_by: ''
    };
    dialogVisible.value = true;
};

// 编辑公司信息
const handleEdit = (row) => {
    isEdit.value = true;
    // 根据formData的属性，将row中的数据赋值给formData
    
    for (let key in formData.value) {
        formData.value[key] = row[key];      
    }
    // 设置update_by为当前登录用户
    formData.value.update_by = store.login_name;

    dialogVisible.value = true;
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该公司信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    .then(async () => {
        // 调用接口，删除公司信息
        await delete_company({ creditcode: row.creditcode }).then(res => {
            if (res.data.detail.status == '202') {
                ElMessage.error(res.data.detail.message);
                return;
            }else if (res.data.detail.status === '200') {
                ElMessage.success(res.data.detail.message);
            }
        })
        const index = tableData.value.findIndex((item) => item.creditcode === row.creditcode);
        if (index > -1) {
            tableData.value.splice(index, 1);
        }
    })
    .catch(() => { });
};

const handleSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 调用接口，更新公司信息
                update_company(formData.value).then(res => {
                    if (res.data.detail.status == '202') {
                        ElMessage.error(res.data.detail.message);
                        return;
                    } else if (res.data.detail.status === '200') {
                        ElMessage.success(res.data.detail.message);
                        // 更新tableData中对应的数据
                        const index = tableData.value.findIndex((item) => item.creditcode === formData.value.creditcode);
                        if (index > -1) {
                            tableData.value[index] = { ...formData.value };
                        }
                    }
                })
            } else {
                // 调用接口，新增公司信息
                add_company(formData.value).then(res => {
                    if (res.data.detail.status == '202') {
                        ElMessage.error(res.data.detail.message);
                        return;
                    }
                    else if (res.data.detail.status === '200') {
                        ElMessage.success(res.data.detail.message);
                        // 将新增数据添加到tableData中
                        tableData.value.push({ ...formData.value });
                    }
                })
            }
            dialogVisible.value = false;
        } else {
            ElMessage.error('请正确填写信息');
        }
    });
};
</script>

<template>
    <!-- 页面内容 -->
    <div class="w-full h-full">
        <el-card>
            <!-- 顶部操作区 -->
            <template #header>
                <div class="card-header flex items-center justify-between">
                    <el-button type="primary" size="small" class="!rounded-button" @click="handleAdd">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>新增公司
                    </el-button>
                    <div class="flex items-center">
                        <div class="relative">
                            <input v-model="searchKeyword" type="text"
                                class="w-64 rounded-lg border border-gray-200 py-1 pl-10 pr-10 text-sm focus:border-blue-500 focus:outline-none"
                                placeholder="请输入关键字搜索" />
                        </div>
                    </div>
                </div>
            </template>
            <!-- 表格区域 -->
            <el-table :data="filteredTableData" stripe>
                <el-table-column prop="companyname" label="公司名称" align="center" show-overflow-tooltip />
                <el-table-column prop="creditcode" label="信用代码" align="center" show-overflow-tooltip />
                <el-table-column prop="subdistrict" label="街道" align="center" width="100" show-overflow-tooltip />
                <el-table-column prop="address" label="公司地址" align="center" show-overflow-tooltip />
                <el-table-column prop="linkman" label="联系人" align="center" width="80" show-overflow-tooltip />
                <el-table-column prop="phone" label="联系号码" align="center" width="120" show-overflow-tooltip />
                <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
                <el-table-column label="操作" align="center" width="110">
                    <template #default="{ row }">
                        <el-button size="small" type="primary" class="!rounded-button" @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button size="small" type="danger" class="!rounded-button" @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-4 flex justify-start">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :total="filteredTableData.length" :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next" />
            </div>
        </el-card>
        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑公司' : '新增公司'" width="500px" destroy-on-close>
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="right">
                <el-form-item label="公司名称" prop="companyname" required>
                    <el-input v-model="formData.companyname" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="信用代码" prop="creditcode" required>
                    <el-input v-model="formData.creditcode" placeholder="请输入信用代码" />
                </el-form-item>
                <el-form-item label="街道" prop="subdistrict" required>
                    <el-select v-model="formData.subdistrict" placeholder="请输入街道">
                        <el-option v-for="item in FENGHUA_AREAS" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="公司地址" prop="address" required>
                    <el-input v-model="formData.address" placeholder="请输入公司地址" />
                </el-form-item>
                <el-form-item label="联系人" prop="linkman" required>
                    <el-input v-model="formData.linkman" placeholder="请输入公司联系人" />
                </el-form-item>
                <el-form-item label="联系号码" prop="phone" required>
                    <el-input v-model="formData.phone" placeholder="请输入联系号码" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button class="!rounded-button" @click="dialogVisible = false">取消</el-button>
                    <el-button class="!rounded-button" type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>